const Router = require('koa-router');
const multer = require('koa-multer');
const fs = require('fs');
const path = require('path');
const FileController = require('../controllers/fileController');
const requireAuth = require('../middleware/auth');

const router = new Router();
const fileController = new FileController();

// 确保uploads目录存在
const uploadsDir = path.join(__dirname, '../../uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// 配置multer
const upload = multer({
  storage: multer.diskStorage({
    destination: function (_, __, cb) {
      cb(null, uploadsDir);
    },
    filename: function (_, file, cb) {
      console.log('Multer filename回调被调用，原始文件名:', file.originalname);
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
      const ext = path.extname(file.originalname);
      cb(null, file.fieldname + '-' + uniqueSuffix + ext);
    }
  })
});

// 文件相关路由
router.post('/upload', requireAuth, requireAuth.requireScope(['write']), upload.single('file'), fileController.uploadFile.bind(fileController));
router.get('/list', fileController.getFileList.bind(fileController));
router.delete('/:id', requireAuth, requireAuth.requireScope(['write']), fileController.deleteFile.bind(fileController));

module.exports = router;